package logic

import (
	"common/comRsa"
	"common/dao/model"
	comJwt "common/jwt"
	"common/utils"
	"context"
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"gorm.io/gorm"
	"time"

	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginReq) (*types.UserLoginResp, error) {
	// todo: add your logic here and delete this line
	if req.Account == "" {
		return nil, errors.New("account is empty")
	}
	if req.PassWord == "" {
		return nil, errors.New("PassWord is empty")
	}
	toString, err := utils.Base64ToString(req.PassWord)
	if err != nil {
		return nil, errors.New("账号密码错误 code=1")
	}
	decrypt, err := comRsa.Decrypt(toString)
	if err != nil {
		return nil, err
	}

	var (
		resp = types.UserLoginResp{}
		user = model.User{}
		db   = l.svcCtx.DB
	)
	table := db.Table(model.TableNameUser)
	err = table.Transaction(func(tx *gorm.DB) error {
		err2 := tx.Where("account = ?", req.Account).Where("is_del = 0").Find(&user).Error
		if err2 != nil {
			return err2
		}

		if user.Password != decrypt {
			return errors.New("账号或者密码错误")
		}
		RegisteredClaims := jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().AddDate(0, 0, l.svcCtx.Config.Auth.AccessExpire)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		}
		claims := comJwt.UserStdClaims{
			UUID:             user.UUID,
			RegisteredClaims: RegisteredClaims,
		}

		resp.Token, err = comJwt.GetToken(claims, l.svcCtx.Config.Auth.AccessSecret)
		if err != nil {
			fmt.Println(err)
			return err
		}

		return nil
	})
	if err != nil {
		return nil, err
	}
	return &resp, nil
}
